package com.yytstudy.bd_voice_demo;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

import com.baidu.voicerecognition.android.VoiceRecognitionClient;
import com.baidu.voicerecognition.android.VoiceRecognitionConfig;
import com.baidu.voicerecognition.android.VoiceRecognitionClient.VoiceClientStatusChangeListener;
import com.baidu.voicerecognition.android.ui.BaiduASRDigitalDialog;
import com.baidu.voicerecognition.android.ui.DialogRecognitionListener;

public class MainActivity extends Activity implements OnClickListener {

	private TextView tvVoice;
	BaiduASRDigitalDialog mDialog;
	VoiceRecognitionClient mClient;
	VoiceRecognitionConfig mConfig;
	private Button btnUIVoice, btnAPIVoice;
	Bundle params = new Bundle();

	// HandlerMessageCode mHandler = new HandlerMessageCode();

	final Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg)
		{
			switch (msg.what) {
			case HandlerMessageCode.GET_API_DATA:
				Bundle data = msg.getData();
				String strData = (String) data.get("apiData");
				System.out.println("111111111111" + strData);
				 tvVoice.setText(strData);
				break;

			default:
				break;
			}
		}

	};

	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		initView();
	}

	@Override
	protected void onDestroy()
	{
		super.onDestroy();
		if (mDialog != null) {
			mDialog.dismiss();
		}
	}

	/**
	 * @Title: initView
	 * @Description: TODO
	 * @param 设定文件
	 * @author 杨彦韬
	 * @return void 返回类型
	 * @throws
	 */
	private void initView()
	{
		btnUIVoice = (Button) findViewById(R.id.btn_ui_voice);
		btnAPIVoice = (Button) findViewById(R.id.btn_api_voice);
		tvVoice = (TextView) findViewById(R.id.tv_bd_voice);

		btnUIVoice.setOnClickListener(this);
		btnAPIVoice.setOnClickListener(this);

		// 设置百度的API_KEY
		params.putString(BaiduASRDigitalDialog.PARAM_API_KEY, Resource.BDVOICE_API_KEY);
		// 设置百度的SERECT_KEY
		params.putString(BaiduASRDigitalDialog.PARAM_SECRET_KEY, Resource.BDVOICE_SERECT_KEY);
		// 设置识别领域，默认为输入
		params.putInt(BaiduASRDigitalDialog.PARAM_PROP, VoiceRecognitionConfig.PROP_INPUT);
		// 设置识别的语言，默认为中文普通话
		params.putString(BaiduASRDigitalDialog.PARAM_LANGUAGE, VoiceRecognitionConfig.LANGUAGE_CHINESE);
		// 设置语言解析
		if (btnAPIVoice.isClickable()) {
			params.putInt(BaiduASRDigitalDialog.PARAM_PROP, VoiceRecognitionConfig.PROP_SEARCH);
			params.putBoolean(BaiduASRDigitalDialog.PARAM_NLU_ENABLE, true);

		}
	}

	/**
	 * @Title: userVoice
	 * @Description: 百度语音基本用法
	 * @param 设定文件
	 * @author 杨彦韬
	 * @return void 返回类型
	 * @throws
	 */
	private void userVoice()
	{

		mDialog = new BaiduASRDigitalDialog(MainActivity.this, params);

		// 设置回调
		mDialog.setDialogRecognitionListener(new DialogRecognitionListener() {
			@Override
			public void onResults(Bundle results)
			{
				ArrayList<String> rs = results != null ? results.getStringArrayList(RESULTS_RECOGNITION) : null;

				if (rs != null && rs.size() != 0) {
					for (String s : rs) {
						StringBuffer sb = new StringBuffer();
						sb.append(s + ",");
						Log.i("info1", s);
						tvVoice.setText(sb.toString());
					}
				}
			}
		});
		// 必须加这句，这可是关键
		mDialog.show();
	}

	private void apiFunction()
	{
		mClient = VoiceRecognitionClient.getInstance(MainActivity.this);
		mClient.setTokenApis(Resource.BDVOICE_API_KEY, Resource.BDVOICE_SERECT_KEY);
		mConfig = new VoiceRecognitionConfig();
		mConfig.setProp(VoiceRecognitionConfig.PROP_SEARCH);
		mConfig.enableNLU();
		MyVoiceRecogListener mListener = new MyVoiceRecogListener(MainActivity.this);
		mClient.startVoiceRecognition(mListener, mConfig);

		// System.out.println("0000000000"+mHandler.getStrHandlerData());
		// tvVoice.setText(mHandler.getStrHandlerData());
	}

	// 继承了VoiceRecogListener的内部类
	class MyVoiceRecogListener implements VoiceClientStatusChangeListener {
		String strData = new String();
		MainActivity activity;

		public MyVoiceRecogListener(MainActivity activity) {

			this.activity = activity;
		}

		@Override
		public void onClientStatusChange(int status, Object obj)
		{
			StringBuffer sb = new StringBuffer();
			switch (status) {
			case VoiceRecognitionClient.CLIENT_STATUS_START_RECORDING:
				sb.append("\n 开始录音……");
				break;
			case VoiceRecognitionClient.CLIENT_STATUS_SPEECH_START:
				sb.append("\n 开始识别……");
				break;
			case VoiceRecognitionClient.CLIENT_STATUS_AUDIO_DATA:
				sb.append("\n 获取数据……");
				break;
			case VoiceRecognitionClient.CLIENT_STATUS_FINISH:
				// sb.append("\n 完成……");
				if (obj != null) {
					List lstResult = (List) obj;
					String strResult = Arrays.toString(null == lstResult ? null : lstResult.toArray());
					sb.append("\n " + strResult);

					try {
						JSONArray jsonArrayData = new JSONArray(strResult);
						JSONArray s = jsonArrayData.getJSONObject(0).getJSONArray("item");
						String strData = s.getString(0);// 获取结果中的第一个

						Message message = new Message();
						message.what = HandlerMessageCode.GET_API_DATA;
						Bundle data = new Bundle();

						data.putString("apiData", strData);
						message.setData(data);
						mHandler.sendMessage(message);
					} catch (JSONException e) {
						// TODO Auto-generated catch block

						e.printStackTrace();
					}

				}
				Log.i("info1", sb.toString());
				break;
			case VoiceRecognitionClient.CLIENT_STATUS_USER_CANCELED:
				break;
			default:
				break;
			}
			// strData = sb.toString();
			// if (strData.length() == 0) {
			// strData = "";
			//
			// }
			// mHandler = new Handler();
			// Message message = new Message();
			// message.what = HandlerMessageCode.GET_API_DATA;
			// Bundle data = new Bundle();
			// data.putString("apiData", strData);
			// message.setData(data);
			// mHandler.sendMessage(message);

		}

		@Override
		public void onError(int arg0, int arg1)
		{
			// TODO Auto-generated method stub

		}

		@Override
		public void onNetworkStatusChange(int arg0, Object arg1)
		{
			// TODO Auto-generated method stub

		}

	}

	
	
	@Override
	public void onClick(View view)
	{
		switch (view.getId()) {
		case R.id.btn_ui_voice:
			userVoice();
			break;
		case R.id.btn_api_voice:
			apiFunction();
		default:
			break;
		}
	}

}
